<?php
namespace app\api\logic;

use app\api\services\OrderService;
use app\api\services\SupplyService;
use app\common\libs\Singleton;
use app\common\models\Community\CommunityTasksLog;
use app\common\models\Order\Order as OrderModel;
use app\common\models\Order\OrderGoods as OrderGoodsModel;
use app\common\models\Order\OrderRefund as OrderRefundModel;
use app\common\models\Order\OrderShop as OrderShopModel;

/**
 * Class OrderRefundLogic
 * @package app\api\logic
 */
class OrderRefundLogic extends BaseLogic
{
    use Singleton;

    public $error = '';
    public function processe($refundStatus)
    {
        if ($refundStatus == 0) {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => 0, 'text' => '处理中'],
                ['value' => 1, 'text' => '财务退款'],
                ['value' => 1, 'text' => '已完成'],
            ];
        } else if ($refundStatus == 1) {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => -1, 'text' => '处理中'],
                ['value' => 1, 'text' => '已拒绝'],
            ];
        } elseif ($refundStatus == 2) {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => -1, 'text' => '处理中'],
                ['value' => 0, 'text' => '财务退款'],
                ['value' => 1, 'text' => '已完成'],
            ];
        } elseif ($refundStatus == 3) {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => -1, 'text' => '处理中'],
                ['value' => -1, 'text' => '财务退款'],
                ['value' => 0, 'text' => '已完成'],
            ];
        } elseif ($refundStatus == 4) {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => -1, 'text' => '处理中'],
                ['value' => 1, 'text' => '已取消'],
            ];
        } else {
            return [
                ['value' => -1, 'text' => '申请退款'],
                ['value' => 0, 'text' => '处理中'],
                ['value' => 1, 'text' => '财务退款'],
                ['value' => 1, 'text' => '已完成'],
            ];
        }
    }

    public function lists($userinfo, $param)
    {
        $where = [
            'user_id' => $userinfo->id,
            'deleted' => 0,
        ];
        // 售后单状态(0进行中 1 已拒绝 2 财务退款  3 已完成 4已取消)
        $status = $param['status'] ?? null;
        if ($status != null && is_numeric($status)) {
            $where['status'] = $status;
        }
        // idx_UserId_Deleted_Status_CreateAt
        $page = OrderRefundModel::getInstance()
            ->where($where)
            ->order('create_at desc')
            ->paginate(input('pageSize', 10));
        return $page;
    }

    public function apply($user_id, $type, $orderNo, $order_goods_id, $option)
    {
        // 售后类型(1退款 （订单发货前） 10退货退款 20 仅退款（订单发货后） 30 换货
        if ( ! in_array($type, [1, 10, 20, 30])) {
            $this->error = '不支持的售后类型';
            return false;
        }
        if (empty($orderNo)) {
            $this->error = '参数必须';
            return false;
        }
        // uk_UserId_OrderGoodsId_OrdereNo
        $refund = OrderRefundModel::getInstance()
            ->where('user_id', $user_id)
            ->where('order_no', $orderNo)
            ->find();

        $nowRefundStatus = 0;
        // 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
        $refundStatus = $refund['status'] ?? null;
        if (is_null($refundStatus) == false && in_array($refundStatus, [0, 1, 2, 3, 5])) {
            return [
                'orderRefundId' => $refund['order_refund_id'],
                // 'processes'     => OrderRefundLogic::getInstance()->processe(
                //     $refundStatus
                // ),
            ];
        }

        $order = OrderService::getInstance()->getOrderInfo(
            $orderNo,
            $user_id);
        if (empty($order)) {
            $this->error = '订单ID有误';
            return false;
        }
        $pay_at = $order['payAt'];
        if (empty($pay_at)) {
            $this->error = '订单未支付';
            return false;
        }
        // TODO 根据商品类型设置售后期 leeyi 2024-05-23
        // 订单售后期
        $repair_guarantee_day = 7;

        $expire_at = strtotime($pay_at) + $repair_guarantee_day * 86400;
        /*if (time() > $expire_at) {
            $this->error = '订单已过售后期';
            return false;
        }*/

        $where = [
            ['order_no','=',$orderNo],
        ];
        $count = CommunityTasksLog::getInstance()->where($where)->count();
        if($count > 0){
            $this->error = '社区任务订单不支持售后退款';
            return false;
        }

        $supply_refund_no = '';
        // var_dump($order['goodsList']);exit;
        // 1线下直付单2线上单3线下单4供应链
        $orderType = $order['orderType'];
        if ($orderType == 4) {
            $reason = $option['applyDesc'] ?? '';
            //售后类型(1退款 （订单发货前） 10退货退款 20 仅退款（订单发货后） 30 换货
            if (empty($order['deliverAt'])) { // 发货前
                $supplyOrderNo = $order['supplyOrderNo'] ?? '';

                $rDetail = empty($supplyOrderNo) ? ['data' => ['orderStatus' => 20]] : \app\api\services\SupplyService::getInstance()->getOrderDetail($supplyOrderNo);
                // 订单状态: 10-已提交待付款,20-已付款待发,30-已发货待收货,40-确认收货交易成功,50-用户超时未支付订单自动取消,70-订单发货前售后关闭,80-订单发货后售后关闭
                $rOrderStatus = $rDetail['data']['orderStatus'] ?? 0;
                if ($rOrderStatus == 20) {
                    $type            = 1;
                    $returnType      = 1;
                    $refundReasonId  = 19;
                    $nowRefundStatus = 3;
                } else {
                    $returnType     = 2;
                    $refundReasonId = 24;
                    // $nowRefundStatus = 2;
                }
            } else if ($type == 10) {
                $returnType     = 2;
                $refundReasonId = 24;
                // $nowRefundStatus = 2;
            } else if ($type == 20) {
                $returnType     = 4;
                $refundReasonId = 40;
                // $nowRefundStatus = 3;
            } else if ($type == 30) {
                $returnType     = 3;
                $refundReasonId = 29;
                // $nowRefundStatus = 2;
            }
            $goodsList = json_decode($order['goodsList'], true);
            $orderSn   = $order['supplyOrderNo']; // 第三方订单号
            // var_dump($orderSn, $goodsList);exit;
            //
            $goodsList2 = [];
            foreach ($goodsList as $item) {
                $goodsList2[] = [
                    'goodsQuantity' => $item['goodsQty'],
                    'goodsSpecId'   => $item['skuId'],
                ];
            }
            $res = SupplyService::getInstance()->applyRefund(
                $reason,
                $orderSn,
                $refundReasonId,
                $returnType,
                $goodsList2);
            // var_dump($res);exit;
            trace(['orderSn' => $orderSn, 'res' => $res]);
            $status = $res['status'] ?? 0;
            if ($status != 200) {
                $this->error = $res['msg'] ?? '操作失败';
                return false;
            }
            $supply_refund_no = $res['data']['returnSn']; // 订单退款售后单号
        } else {
            if (empty($order['deliverAt'])) { // 发货前
                $nowRefundStatus = 3;
                $type            = 1;
            }
        }

        $shopId = \think\facade\Db::table('order_goods')
            ->where('order_no', $orderNo)
        // ->where('goods_id', $order_goods_id)
            ->where('deleted', 0)
            ->value('shop_id');

        // 退款金额 (未发货退款金额为支付金额；已发货扣除邮费)
        $refund_money = empty($order['deliverAt']) ? $order['payPrice'] : $order['payPrice'] - $order['postage'];

        $goods_quantity = \think\facade\Db::table('order_goods')
            ->where('order_no', $orderNo)
        // ->where('goods_id', $order_goods_id)
            ->where('deleted', 0)
            ->sum('quantity');
        $refund_no  = getNo('RO');
        $attach     = $option['attach'] ?? [];
        $insertData = [
            'shop_id'          => $shopId, //
            'refund_no'        => $refund_no,
            'order_no'         => $orderNo, //
            'order_goods_id'   => (int) $order_goods_id, //
            'user_id'          => $user_id, //
            'type'             => $type, //
            'refund_money'     => $refund_money,
            'goods_quantity'   => $goods_quantity,
            'order_status'     => $order['status'], // 原订单状态，便于取消售后的时候，订单状态复位
            'apply_desc'       => $option['applyDesc'] ?? '', //
            'attach'           => empty($attach) ? '[]' : json_encode($attach, 320),
            'supply_refund_no' => $supply_refund_no,
            // 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
            'status'           => $nowRefundStatus,
            // 商家审核状态(0待审核 10已同意 20已拒绝)
            'is_agree'         => in_array($nowRefundStatus, [2, 3]) ? 10 : 0,
        ];
        // var_dump($insertData);exit;
        // 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        // 启动事务
        \think\facade\Db::startTrans();
        try {
            OrderModel::where('order_no', $orderNo)->update([
                'status' => 5,
            ]);
            OrderShopModel::where('order_no', $orderNo)->update([
                'status' => 5,
            ]);
            OrderGoodsModel::where('order_no', $orderNo)->update([
                'status' => 5,
            ]);
            $orderRefundId = OrderRefundModel::getInstance()->insertGetId($insertData);
            // 提交事务
            \think\facade\Db::commit();
            return [
                'orderRefundId' => $orderRefundId,
                // 'refundTypeArr'   => OrderRefundModel::getInstance()->typeArr,
                // 'refundStatusArr' => OrderRefundModel::getInstance()->statusArr,
                // 'processes'     => OrderRefundLogic::getInstance()->processe($refundStatus),
            ];
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
        }
        return false;
    }

    /**
     * 用户取消售后申请
     * @param $data
     * @return false|int
     */
    public function cancel($model, $data)
    {
        if (empty($model)) {
            $this->error = '售后单有误';
            return false;
        }
        // is_agree 商家审核状态(0待审核 10已同意 20已拒绝)
        // is_user_send 用户是否发货(0未发货 1已发货)
        // if ($model['is_agree'] == 10) {
        //     $this->error = '商家已同意';
        //     return false;
        // }
        // 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
        if ($model['status'] == 4) {
            $this->error = '';
            return true;
        }
        if ($model['status'] == 3) {
            $this->error = '售后单已退货，不能取消申请';
            return false;
        }
        if ($model['status'] == 5) {
            $this->error = '售后单已完成，不能取消申请';
            return false;
        }
        // 1线下直付单 2线上单 3线下单 4供应链
        $order_type = OrderModel::where('order_no', $model['order_no'])->value('order_type');
        if ($order_type == 4) {
            $returnSn = $model['supply_refund_no'];
            // var_dump($returnSn);exit;
            $res = SupplyService::getInstance()->cancelRefund($returnSn);
            // var_dump($res);exit;
            trace(['returnSn' => $returnSn, 'res' => $res]);
            $status = $res['status'] ?? 0;
            if ($status != 200) {
                $this->error = $res['msg'] ?? '操作失败';
                return false;
            }
        }
        // 启动事务
        \think\facade\Db::startTrans();
        try {
            OrderModel::where('order_no', $model['order_no'])->update([
                'status' => $model['order_status'], // 复位订单状态
            ]);
            OrderShopModel::where('order_no', $model['order_no'])->update([
                'status' => $model['order_status'], // 复位订单状态
            ]);
            OrderGoodsModel::where('order_no', $model['order_no'])->update([
                'status' => $model['order_status'], // 复位订单状态
            ]);
            $res = OrderRefundModel::getInstance()
                ->where('user_id', $model['user_id'])
                ->where('order_refund_id', $model['order_refund_id'])
                ->save([
                    'status'      => 4,
                    'update_at'   => date('Y-m-d H:i:s'),
                    'finish_time' => date('Y-m-d H:i:s'),
                ]);
            // 提交事务
            \think\facade\Db::commit();
            return $res;
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
        }
        return false;
    }

    /**
     * 用户发货
     * @param $data
     * @return false|int
     */
    public function delivery($model, $data)
    {
        if (empty($model)) {
            $this->error = '售后单有误';
            return false;
        }
        // is_user_send 用户是否发货(0未发货 1已发货)
        if ($model['is_user_send'] == 1) {
            return true;
        }

        // is_agree 商家审核状态(0待审核 10已同意 20已拒绝)
        if ($model['is_agree'] == 0) {
            $this->error = '待商家审核';
            return false;
        }
        if ($model['is_agree'] == 20) {
            $this->error = '商家已拒绝';
            return false;
        }

        if (empty($data['expressName'])) {
            $this->error = '请填写物流名称';
            return false;
        }
        // if (empty($data['expressCode'])) {
        //     $this->error = '请选择物流公司';
        //     return false;
        // }
        if (empty($data['expressNo'])) {
            $this->error = '请填写物流单号';
            return false;
        }
        // 1线下直付单 2线上单 3线下单 4供应链
        $order_type = OrderModel::where('order_no', $model['order_no'])->value('order_type');
        // var_dump($model['supply_refund_no'], $order_type, $data['expressNo'], $data['expressName']);exit;
        if ($order_type == 4) {
            $returnSn = $model['supply_refund_no'];
            // var_dump($returnSn);exit;
            $res = SupplyService::getInstance()->sendReturnGoods(
                $data['expressNo'],
                $data['expressName'],
                $returnSn);
            // var_dump($res);exit;
            trace(['returnSn' => $returnSn, 'res' => $res]);
            $status = $res['status'] ?? 0;
            if ($status != 200) {
                $this->error = $res['msg'] ?? '操作失败';
                return false;
            }
        }
        // 售后单状态(0进行中 1 已拒绝 2 审核通过  3 已退货 4已取消 5 已完成)
        return OrderRefundModel::getInstance()
            ->where('user_id', $model['user_id'])
            ->where('order_refund_id', $model['order_refund_id'])
            ->save([
                'is_user_send' => 1,
                'status'       => 3,
                'send_time'    => date('Y-m-d H:i:s'),
                'express_name' => $data['expressName'],
                'express_code' => $data['expressCode'] ?? '',
                'express_no'   => $data['expressNo'],
            ]);
    }
}
